from appium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

desired_caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "platformVersion": "9",
    "deviceName": '192.168.2.9:5555',
    "appPackage": "com.seven.qaml.burstserven",
    "appActivity": "com.seven.qaml.burstserven.ui.LoginActivity",
    'skipServerInstallation': False,
    'skipDeviceInitialization': False,
    "noReset": True
}

appium_server_url = 'http://127.0.0.1:4723'
driver = webdriver.Remote(appium_server_url, desired_caps)
driver.implicitly_wait(10)  # 设置全局隐式等待时间


def check_and_click_template_button():
    try:
        if driver.find_elements(By.ID, 'com.seven.qaml.burstserven:id/title_template'):
            button = driver.find_element(By.ID, 'com.seven.qaml.burstserven:id/button1')
            button.click()
            logging.info("检测到 title_template，已点击 button1")
    except Exception as e:
        logging.error(f"点击 title_template 时出错: {e}")


def safe_click(element_id, timeout=15):
    for attempt in range(1,4):  # 最多重试3次
        try:
            element = WebDriverWait(driver, timeout).until(
                EC.element_to_be_clickable((By.ID, element_id))
            )
            element.click()
            return True
        except StaleElementReferenceException:
            logging.warning(f"[警告] 元素 {element_id} 失效，正在重试... (尝试 {attempt}/3)")
    logging.error(f"[错误] 元素 {element_id} 无法点击，请检查页面状态。")
    return False


def wait_for_element(element_id, timeout=10):
    try:
        WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.ID, element_id))
        )
        return True
    except TimeoutException:
        logging.error(f"[错误] 等待元素 {element_id} 超时")
        return False


def press_back(times=10, interval=0.1):
    for i in range(times):
        sleep(interval)
        driver.keyevent(4)
        check_and_click_template_button()


count = 0
while count < 200:
    check_and_click_template_button()

    if not safe_click('com.seven.qaml.burstserven:id/ll_menuScan_delaySchemeContainer'):
        logging.warning("未找到 ll_menuScan_delaySchemeContainer，跳过本次循环")
        continue

    if not safe_click('com.seven.qaml.burstserven:id/btn_delay_add_group'):
        logging.warning("未找到 btn_delay_add_group，跳过本次循环")
        continue

    press_back(times=10, interval=0.1)

    if wait_for_element('com.seven.qaml.burstserven:id/text_ver'):
        driver.keyevent(66)
    else:
        logging.warning("未找到 text_ver，可能页面加载异常")

    count += 1
    logging.info(f"已完成 {count} 次循环")

logging.info('自动化流程执行完毕')
